#ifndef FIFOBUFFER_HPP
#define FIFOBUFFER_HPP

#include <stddef.h>

template <typename T, size_t BUFFER_SIZE>
class FIFOBuffer {
public:
    FIFOBuffer()
        : head(0), tail(0), _size(0) {}

    void push(const T& value) {
        if (_size < BUFFER_SIZE) {
            buffer[tail] = value;
            tail = (tail + 1) % BUFFER_SIZE;
            ++_size;
        }
    }

    T pop() {
        if (_size > 0) {
            T value = buffer[head];
            head = (head + 1) % BUFFER_SIZE;
            --_size;
            return value;
        } else {
            // 缓冲区为空，处理此情况
            return T();
        }
    }

    T at(size_t index) const {
        return buffer[(head + index) % BUFFER_SIZE];
    }

    bool empty() const { return _size == 0; }
    bool full() const { return _size == BUFFER_SIZE; }
    size_t size() const { return _size; }
    T& front() { return buffer[head]; }
    T& back() { return buffer[(tail + BUFFER_SIZE - 1) % BUFFER_SIZE]; }

    void clear() {
        head = 0;
        tail = 0;
        _size = 0;
        memset(buffer, 0, sizeof(T) * BUFFER_SIZE);
    }

    // 迭代器类
    class Iterator {
    public:
        Iterator(FIFOBuffer& buffer, size_t pos)
            : buffer(buffer), pos(pos), count(0) {}

        Iterator& operator++() {
            pos = (pos + 1) % BUFFER_SIZE;
            ++count;
            return *this;
        }

        bool operator!=(const Iterator& other) const {
            return pos != other.pos || count != other.count;
        }

        T& operator*() {
            return buffer.buffer[pos];
        }

    private:
        FIFOBuffer& buffer;
        size_t pos;
        size_t count;
    };

    Iterator begin() { return Iterator(*this, head); }
    Iterator end() { return Iterator(*this, tail); }

private:
    T buffer[BUFFER_SIZE];
    size_t head, tail, _size;
};

#endif // FIFOBUFFER_HPP